﻿//using Hotel.HFramework.LogManager;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hotel.Booking.ReservationWS.Common.Utility
{
    public class GZipUtility
    {
        public static string GZipCompress(string origin)
        {
            string result = origin;
            try
            {
                if (!string.IsNullOrEmpty(origin))
                {
                    byte[] originBuf = Encoding.UTF8.GetBytes(origin);
                    using (var outstream = new MemoryStream())
                    {
                        using (var zipStream = new GZipStream(outstream, CompressionMode.Compress, true))
                        {
                            zipStream.Write(originBuf, 0, originBuf.Length);
                            zipStream.Close();

                            StringBuilder sb = new StringBuilder();
                            foreach (byte b in outstream.ToArray())
                            {
                                sb.AppendFormat("{0:X2}", b);
                            }
                            result = sb.ToString();
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                //HotelTraceLogManager.WriteWSWarnLog("GZipCompress Error", ex);
            }

            return result;
        }


        public static string GZipDecompress(string origin)
        {
            string result = origin;

            try
            {
                if (!string.IsNullOrEmpty(origin))
                {
                    var inputBytes = new byte[origin.Length / 2];
                    for (var x = 0; x < inputBytes.Length; x++)
                    {
                        var i = Convert.ToInt32(origin.Substring(x * 2, 2), 16);
                        inputBytes[x] = (byte)i;
                    }

                    using (MemoryStream inputStream = new MemoryStream(inputBytes))
                    {
                        using (MemoryStream outStream = new MemoryStream())
                        {
                            using (GZipStream zipStream = new GZipStream(inputStream, CompressionMode.Decompress))
                            {
                                zipStream.CopyTo(outStream);
                                zipStream.Close();
                                return Encoding.UTF8.GetString(outStream.ToArray());
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                //HotelTraceLogManager.WriteWSWarnLog("GZipCompress Error", ex);
            }

            return result;
        }
    }
}
